﻿// <copyright file="CompositionHostEx.cs" company="Microsoft Corporation">
// Copyright (c) 2010 Microsoft Corporation All Rights Reserved
// </copyright>
// <author>Michael S. Scherotter</author>
// <email>mischero@microsoft.com</email>
// <date>2010-09-14</date>
// <summary>Composition Host Extension</summary>

namespace Microsoft.WebAnalytics.Hosting
{
    using System;
    using System.ComponentModel.Composition.Hosting;
    using System.ComponentModel.Composition.Primitives;

    /// <summary>
    /// MEF Composition Host wrapper that allows re-composition as an option)
    /// </summary>
    public static class CompositionHostEx
    {
        #region Fields
        /// <summary>
        /// The singleton container
        /// </summary>
        private static CompositionContainer container;
        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets a value indicating whether the host been initialized?
        /// </summary>
        public static bool IsInitialized { get; set; }

        #endregion

        /// <summary>
        /// Initialize the Composition host with a list of catalogs
        /// </summary>
        /// <param name="catalogs">the compose-able part catalog</param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Not relevant.")]
        public static void Initialize(params ComposablePartCatalog[] catalogs)
        {
            var catalog = new AggregateCatalog(catalogs);
            var container = new CompositionContainer(catalog);
            Initialize(container);

            IsInitialized = true;
        }

#if WINDOWS_PHONE
#else
        /// <summary>
        /// Initialize the Composition host with a default deployment catalog
        /// </summary>
        public static void Initialize()
        {
            Initialize(new DeploymentCatalog());

            IsInitialized = true;
        }
#endif
        /// <summary>
        /// Initialize the composition host
        /// </summary>
        /// <param name="compositionContainer">the composition container</param>
        public static void Initialize(CompositionContainer compositionContainer)
        {
            CompositionHost.Initialize(compositionContainer);
            container = compositionContainer;

            IsInitialized = true;
        }

        /// <summary>
        /// Get the Singleton container
        /// </summary>
        /// <returns>the single Composition Container</returns>
        internal static CompositionContainer GetContainer()
        {
            if (container == null)
            {
                throw new ArgumentNullException("Initialize has not been called on CompositionInitializer");
            }

            return container;
        }
    }
}
